package com.foogui.demo.async;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

@Slf4j
public class AsyncProducer {

    public static void main(String[] args) throws Exception {
        //1.创建消息生产者producer，并指定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("produce_group");
        //2.指定Nameserver地址
        producer.setNamesrvAddr("localhost:9876");
        // 指定异步发送失败后不进行重试发送
        producer.setRetryTimesWhenSendAsyncFailed(0);
        //3.启动producer
        producer.start();

        for (int i = 0; i < 10; i++) {
            //4.创建消息对象，指定主题Topic、Tag和消息体
            Message msg = new Message("topic1", "async", ("Hello World 异步发送消息：" + i).getBytes());
            //5.发送异步消息,需要注册回调函数
            producer.send(msg, new SendCallback() {
                @Override
                public void onSuccess(SendResult result) {
                    log.info("发送结果：" + result.getSendStatus());
                }

                @Override
                public void onException(Throwable e) {
                    log.info("发送异常：" + e);
                }
            });


        }
        // 由于采用的是异步发送，所以若这里不sleep，
        // 则消息还未发送就会将producer给关闭，报错
        TimeUnit.SECONDS.sleep(3);
        //6.关闭生产者producer
        producer.shutdown();
    }
}
